package cp.remote.timer;

import android.os.Handler;
import cp.remote.activity.Load_Activity;
import cp.remote.config.ActivityConfig;
import cp.remote.config.NetworkConfig;
import cp.remote.network.TaskSwitch;

public class LoadTimer implements Runnable {

    private boolean sended = false, stop = false, cmd = false;
    private String page = "";
    private int count = 0;
    private Load_Activity act;
    private Handler h;

    public LoadTimer(Load_Activity act, String page, Handler h) {
        this.page = page;
        this.act = act;
        this.h = h;
    }

    public void run() {
        if (count == ActivityConfig.maxloadtry) {
            act.cancelLoadingTheActivity();
            return;
        }
        if (sended) {
            if (NetworkConfig.nettask.isLastCommandOk()) {
                act.setProgressText("Sending OK");
                sended = false;
                count = 0;
                if (stop) {
                    cmd = true;
                    act.finishLoadingTheActivity();
                } else
                    stop = true;
            } else if (NetworkConfig.nettask.isError()) {
                act.setProgressText("Error: "
                        + NetworkConfig.nettask.getErrormsg());
                sended = false;
                count++;
            }
        } else {
            if (stop) {
                act.setProgressText(msg(page));
                NetworkConfig.nettask.send(page);
                sended = true;
            } else {
                act.setProgressText(msg("Stop"));
                NetworkConfig.nettask.send(TaskSwitch.STOP);
                sended = true;
            }
        }
        if (!cmd)
            h.postDelayed(this, 100);
    }

    private String msg(String command) {
        return "Try: " + (count + 1) + " from " + ActivityConfig.maxloadtry
                + " Send " + command + " Signal";
    }

}
